package com.diaohw.platform.framework.authorization;

import cn.dev33.satoken.config.SaTokenConfig;
import cn.dev33.satoken.stp.StpUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.function.Function;

@Slf4j
@Component
@Order
public class OnlineManager {

    public static final String LOGIN_ACCOUNT_ID = "LOGIN:ACCOUNT:ID";
    public static final Function<String, String> LOGIN_ACCOUNT_INFO = accountId -> "LOGIN:ACCOUNT:INFO:" + accountId;


    @Resource
    private SaTokenConfig config;

    /**
     * 标记：是否已初始化成功
     */
    @Autowired
    @Qualifier("aloneRedisTemplate")
    private StringRedisTemplate template;


    /**
     * 刷新用户在线时间
     *
     * @param accountId 用户ID
     */
    protected void refresh(String accountId) {
        StpUtil.updateLastActivityToNow();
        long score = System.currentTimeMillis();
        template.opsForZSet().add(LOGIN_ACCOUNT_ID, accountId, score);
    }

    /**
     * 在线用户ID列表
     */
    public Set<String> online() {
        long timeout = config.getActivityTimeout();
        long max = System.currentTimeMillis();
        long min = max - timeout * 1000;
        return online(min, max);
    }

    /**
     * 休眠时间
     */
    public long timeout() {
        return config.getActivityTimeout();
    }

    /**
     * 在线用户列表
     */
    public Set<String> online(long min, long max) {
        return template.opsForZSet().rangeByScore(LOGIN_ACCOUNT_ID, min, max);
    }

    /**
     * 下线
     *
     * @param loginId 用户ID
     */
    public void logout(String loginId) {
        template.delete(LOGIN_ACCOUNT_INFO.apply(loginId));
        template.opsForZSet().remove(LOGIN_ACCOUNT_ID, loginId);
        StpUtil.kickout(loginId);

    }
}
